%%%-------------------------------------------------------------------
%%% @author Administrator
%%% @copyright (C) 2023, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 13. 4月 2023 15:15
%%%-------------------------------------------------------------------
-module(simple_cache).
-export([insert/2,insert/3, lookup/1, delete/1]).
insert(Key, Value) ->
  case sc_store:lookup(Key) of % ❶ 检查键是否已经存在
    {ok, Pid} ->
      sc_element:replace(Pid, Value);
    {error, _} ->
      {ok, Pid} = sc_element:create(Value),
      sc_store:insert(Key, Pid),
      sc_event:create(Key, Value) % 投递进程创建
  end.
insert(Key, Value,Time) ->
  case sc_store:lookup(Key) of % ❶ 检查键是否已经存在
    {ok, Pid} ->
      sc_element:replace(Pid, Value);
    {error, _} ->
      {ok, Pid} = sc_element:create(Value,Time),
      sc_store:insert(Key, Pid),
      sc_event:create(Key, Value) % 投递进程创建
  end.
lookup(Key) ->
  try
    {ok, Pid} = sc_store:lookup(Key), % ❷ (以下2行)获取与键相对应的pid
     sc_event:lookup(Key),
    {ok, Value} = sc_element:fetch(Pid),
    {ok, Value}
  catch
    _Class:_Exception ->
      {error, not_found}
  end.
delete(Key) ->
  case sc_store:lookup(Key) of
    {ok, Pid} ->
      sc_element:delete(Pid) ;% ❸ 清理
    {error, _Reason} ->
      ok
  end.
